#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* BuyNode(NodeDataType x)
{
	ListNode* newHead = (ListNode*)malloc(sizeof(ListNode));
	newHead->data = x;
	newHead->next = newHead->prev = newHead;
	return newHead;
}

ListNode* LTInit()
{
	ListNode* phead = BuyNode(-1);
	return phead;
}

void LTPushBack(ListNode* phead, NodeDataType s)
{
	assert(phead);
	ListNode* pcur = BuyNode(s);
	pcur->next = phead;
	pcur->prev = phead->prev;
	phead->prev->next = pcur;
	phead->prev = pcur;
}

void LTPrint(ListNode* phead)
{
	assert(phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTDesTory(ListNode* phead)
{
	assert(phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		ListNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}

void LTPushFront(ListNode* phead, NodeDataType s)
{
	assert(phead);
	ListNode* pcur = BuyNode(s);
	pcur->next = phead->next;
	pcur->prev = phead;
	phead->next->prev = pcur;
	phead->next = pcur;
}

bool IfEmpty(ListNode* phead)
{
	return phead->next == phead;
}

void LTPopBack(ListNode* phead)
{
	assert(phead);
	assert(!IfEmpty(phead));
	ListNode* pcur = phead;
	ListNode* del = pcur->prev;
	del->prev->next = pcur;
	pcur->prev = del->prev;
	free(del);
	del = NULL;
}

void LTPopFront(ListNode* phead)
{
	assert(phead);
	assert(!IfEmpty(phead));
	ListNode* pcur = phead;
	ListNode* del = phead->next;
	del->next->prev = phead;
	phead->next = del->next;
	free(del);
	del = NULL;
}

ListNode* LTFind(ListNode* phead, NodeDataType s)
{
	assert(phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == s)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsertAfter(NodeDataType s, ListNode* pos)
{
	assert(pos);
	ListNode* newNode = BuyNode(s);
	newNode->next = pos->next;
	pos->next->prev = newNode;
	pos->next = newNode;
	newNode->prev = pos;
}

void LTErase(ListNode* phead, ListNode* pos)
{
	assert(pos && phead);
	assert(!IfEmpty(phead));
	ListNode* pcur = phead;
	while (pcur->next != pos)
	{
		pcur = pcur->next;
	}
	pos->next->prev = pcur;
	pcur->next = pos->next;
	free(pos);
	pos = NULL;
}
